;
(function (window, angular) {
  'use strict';
  angular.module("Controller.Maintenance.Customer", [])
    .controller("CustomerCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, UserContextService) {
      $scope.activeFlag = [true, false, false, false, false];
      $scope.markInfo = {
        allChecked: false
      };
      $scope.pageInfo = {
        totalPages: 1,
        totalRows: 0,
        pageSize: 10,
        curPage: 1
      };
      $scope.toolbarConfig = {
        showAdvanceSearch: false,
        showColConfig: false
      };

      $scope.dataList = [];
      $scope.submitted = false;
      $scope.condition = {};

      $scope.tabFlag = {};
      var tabFlag = {
        0: "新增",
        1: "编辑"
      };
      $scope.detailInfo = {
        sex: 1,
      };

      $scope.tbConf = {
        fixedWidth: 440,
        scrollWidth: 760,
        tableCol: [
          {
            name: "积分",
            width: 60,
            dataField: "userScore",
            isShow: true,
            isFixed: false,
          },
          {
            name: "手机号",
            width: 100,
            dataField: "mobilePhone",
            isShow: true,
            isFixed: false,
          },
          {
            name: "姓名",
            width: 100,
            dataField: "cname",
            isShow: true,
            isFixed: false,
          },
          {
            name: "性别",
            width: 60,
            dataField: "sexShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "小程序",
            width: 80,
            dataField: "hasOpenIdShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "来源方式",
            width: 100,
            dataField: "sourceShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "状态",
            width: 60,
            dataField: "statusShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "创建日期",
            dataField: "createdTimeShow",
            width: 140,
            isShow: true,
            isFixed: false,
          },
          {
            name: "操作",
            isShow: true,
            isFixed: true,
          }
        ]
      };

      $scope.setFixedWidth = function () {
        $scope.tbStyle = {
          scrollLeft: {
            left: $scope.tbConf.fixedWidth + "px"
          }
        };
      };

      $scope.changeTab = function (index) {
        $scope.activeFlag = [false, false, false, false, false, false];
        $scope.activeFlag[index] = true;
        $scope.submitted = false;
        switch (index) {
          case 0:
            initData();
            break;
          case 1:
            break;
          case 2:
            break;
          default:
            break;
        }
      };

      function initData() {
        $scope.tabFlag = {};
        $scope.detailInfo = {
          sex: 1,
        };
      }

      $scope.search = function (curpage) {
        getDataList(curpage);
      };

      $scope.reset = function () {
        $scope.condition = {};
      };

      function getDataList(curPage) {
        var service = "mt";
        var reqUrl = "/customer/list";
        var param = {};
        param.pageSize = $scope.pageInfo.pageSize;
        if (!!curPage) {
          $scope.pageInfo.curPage = curPage;
        }
        param.pageNum = $scope.pageInfo.curPage;
        param.filters = $scope.condition;
        ybHttp.Post(service, reqUrl, param).then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return;
          }
          $scope.markInfo.allChecked = false;
          angular.forEach(resp.value.list, function (item) {
            item.isChecked = false;
            item.sexShow = $filter("Sex")(item.sex);
            item.hasOpenIdShow = item.openId ? '已绑定' : '未绑定'
            item.sourceShow = $filter("Source")(item.source);
            item.statusShow = $filter("TrueOrFalse")(item.status, 'status');
            item.createdTimeShow = $filter("YbDate")(item.createdTime, 'yyyy-MM-dd HH:mm:ss');
            item.totalScore =  item?.totalScore  ? parseInt(item?.totalScore) : 0
          });
          $scope.pageInfo.totalRows = resp.value.total;
          $scope.pageInfo.totalPages = resp.value.pages;
          $scope.dataList = resp.value.list;
        });
      }

      $scope.switchToolbar = function (toolbar) {
        if (!!$scope.toolbarConfig["show" + toolbar]) {
          $scope.toolbarConfig["show" + toolbar] = false;
        } else {
          $timeout(function () {
            $scope.toolbarConfig["show" + toolbar] = true;
          });
        }
      };

      $scope.selectRow = function (index) {
        $scope.markInfo.curRow = index
      };

      function checkAll() {
        var selectAll = false;
        for (var i = 0, len = $scope.dataList.length; i < len; i++) {
          if (!$scope.dataList[i].isChecked) {
            selectAll = false;
            break;
          }
          selectAll = true;
        }
        return selectAll;
      }

      $scope.selectSingle = function (item) {
        if (!item.isChecked) {
          $scope.markInfo.allChecked = false;
        } else {
          if (!checkAll()) {
            $scope.markInfo.allChecked = false;
          } else {
            $scope.markInfo.allChecked = true;
          }
        }
      };

      $scope.selectAll = function () {
        for (var i = 0, len = $scope.dataList.length; i < len; i++) {
          $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
        }
      };

      $scope.addData = function () {
        $scope.tabFlag.type = 0;
        $scope.tabFlag.name = tabFlag[0];
        $scope.changeTab(1);
      };

      $scope.editData = function (item) {
        $scope.detailInfo = JSON.parse(JSON.stringify(item));
        $scope.tabFlag.type = 1;
        $scope.tabFlag.name = tabFlag[1];
        $scope.changeTab(1);
      };

      $scope.saveData = function (isValid) {
        if (!isValid) {
          $scope.submitted = true;
          return;
        }
        var service = "mt";
        var reqUrl = "/customer/insert";

        if ($scope.tabFlag.type === 1) {
          reqUrl = "/customer/update";
        }

        ybHttp.Post(service, reqUrl, $scope.detailInfo).then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return;
          }
          ybWidget.ShowToaster('success', '操作成功');
          $scope.changeTab(0);
          getDataList();
        });
      };

      $scope.switchStatus = function (val, statusType) {
        var service = "mt";
        var reqUrl = "";
        var tipMsg = "";

        if (statusType == "0") {
          reqUrl = '/customer/updateDisable'
          tipMsg = "停用";
        } else if (statusType == "1") {
          reqUrl = '/customer/updateEnable'
          tipMsg = "启用";
        }

        ybWidget.ShowMessage("确定" + tipMsg + "该用户吗？", MESG_TYPE.Ask).then(function () {
          ybHttp.Post(service, reqUrl + '?id=' + val).then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            ybWidget.ShowToaster('success', '操作成功');
            getDataList();
          });
        }, function () { });
      };

      $scope.unBindData = function (val) {
        var service = "mt";
        var reqUrl = "/customer/unbind";
        ybWidget.ShowMessage("确定解绑该用户吗？", MESG_TYPE.Ask).then(function () {
          ybHttp.Post(service, reqUrl + '?id=' + val).then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            ybWidget.ShowToaster('success', '操作成功');
            getDataList();
          });
        }, function () { });
      };

      $scope.modifyPhone = function (val) {
        ybWidget.ShowConfirm("确定要需更改手机号吗？", "新手机号", { isMobile: true }).then(function (data) {
          var service = "mt";
          var reqUrl = "/customer/updatePhone";
          var params = {
            id: val,
            mobilePhone: data
          }
          ybHttp.Post(service, reqUrl, params).then(function (resp) {
            if (resp.code !== 0) {
              ybWidget.ShowMessage(resp, MESG_TYPE.Error);
              return;
            }
            ybWidget.ShowToaster('success', '操作成功');
            getDataList();
          });
        });
      };

      $scope.viewBindCars = function (item) {
        var param = {
          type: 'list',
          user: { id: item.id }
        };
        $state.go('app.maintenance.vehicle', param)
      };

      $scope.addCar = function (item) {
        var param = {
          type: 'add',
          user: { id: item.id, name: item.cname, phone: item.mobilePhone }
        };
        $state.go('app.maintenance.vehicle', param)
      };

      $scope.integralLog = function (item) {
        const id = item.id
        ybWidget.IntegralLog({id}).then(function () {
        })
      }
      var btnPermissionCode = {
        VEHICLE_ADD: window.ActionCode.VEHICLE_ADD,
      };

      $scope.btnPermission = {
        VEHICLE_ADD: true,
      };

      function setBtnPermission() {
        for (var key in btnPermissionCode) {
          $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
        }
      }

      (function () {
        UserContextService.SetBtnPermission(setBtnPermission);
        getDataList();
        $scope.setFixedWidth();
      })();
    }]);
})(window, window.angular);